package com.example.bighomework.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.bighomework.R;

public class UpdateActivity extends AppCompatActivity {
    private EditText etAccount, etOldPassword, etNewPassword;
    private Button btnUpdate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);

        // 绑定控件
        etAccount = findViewById(R.id.account1);
        etOldPassword = findViewById(R.id.password2);
        etNewPassword = findViewById(R.id.password3);
        btnUpdate = findViewById(R.id.login2);

        // 修改密码按钮点击事件
        btnUpdate.setOnClickListener(v -> updatePassword());
    }

    private void updatePassword() {
        String account = etAccount.getText().toString().trim();
        String oldPassword = etOldPassword.getText().toString().trim();
        String newPassword = etNewPassword.getText().toString().trim();

        // 验证输入
        if (account.isEmpty() || oldPassword.isEmpty() || newPassword.isEmpty()) {
            Toast.makeText(this, "所有字段都不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // 获取保存的用户信息
        SharedPreferences prefs = getSharedPreferences("user_data", MODE_PRIVATE);
        String savedAccount = prefs.getString("username", "");
        String savedPassword = prefs.getString("password", "");

        // 验证账号和旧密码
        if (!account.equals(savedAccount) || !oldPassword.equals(savedPassword)) {
            Toast.makeText(this, "账号或旧密码错误", Toast.LENGTH_SHORT).show();
            return;
        }

        // 保存新密码
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("password", newPassword);
        editor.apply();

        Toast.makeText(this, "密码修改成功", Toast.LENGTH_SHORT).show();
        finish();
    }
}